
package com.leyou.user.service;

import com.leyou.common.pojo.utils.NumberUtils;
import com.leyou.user.config.JwtProperties;
import com.leyou.user.mapper.AddressMapper;
import com.leyou.user.mapper.UserDetailMapper;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.Address;
import com.leyou.user.pojo.User;
import com.leyou.user.pojo.UserDetail;
import com.leyou.user.pojo.Useron;
import com.leyou.user.utils.CodecUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service

public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserDetailMapper userDetailMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    static final String KEY_PREFIX = "user:code:phone:";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    static final Logger logger = LoggerFactory.getLogger(UserService.class);

    public Boolean checkData(String data, Integer type) {
        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                return null;
        }
        int i = this.userMapper.selectCount(user);
        return i == 0;
    }

    public Boolean sendVerifyCode(String phone) {
        //生成验证码
        String code = NumberUtils.generateCode(6);
        System.out.println(code);
        try {
            //发送短信
            HashMap<String, String> map = new HashMap<>();
            map.put("phone", phone);
            map.put("code", code);
            this.amqpTemplate.convertAndSend("leyou.sms.exchange", "sms.verify.code", map);
            //存入redis
            this.stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }
    }

    public Boolean register(String username, String password, String phone, String code) {

        String c = this.stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (!c.equals(code)) {
            return false;
        }

        String s = CodecUtils.generateSalt();
        password = CodecUtils.md5Hex(password, s);

        User user = new User();
        user.setId(null);
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setCreated(new Date());
        user.setSalt(s);
        int i = this.userMapper.insertSelective(user);
        if (i == 1) {
            this.stringRedisTemplate.delete(KEY_PREFIX + phone);
            return true;
        }
        return false;

    }

    public User queryUserByUsernameAndPassword(String username, String password) {
        User user = new User();
        user.setUsername(username);
        User user1 = this.userMapper.selectOne(user);
        if (user1 == null) {
            return null;
        }
        String salt = user1.getSalt();
        password = CodecUtils.md5Hex(password, salt);
        if (user1.getPassword().equals(password)) {
            return user1;
        }
        return null;
    }

    public List<Address> queryAddressByUid(Long uid) {
        Address address = new Address();
        address.setUid(uid);
        List<Address> addresses = this.addressMapper.select(address);
        return addresses;
    }

    public void addAddress(String token, Address address) throws Exception {

        addressMapper.insertSelective(address);

    }


    public Address queryAddressById(Long id) {
        Address address = this.addressMapper.selectByPrimaryKey(id);
        return address;
    }


    public void updateAddress(Address a) {
        this.addressMapper.updateByPrimaryKey(a);
    }


    public List<Address> queryAddresses(Long id) {
        Address address = new Address();
        address.setUid(id);
        return addressMapper.select(address);
    }

    @Transactional
    public void setDefault(Long uid, Long id) {

        Address address1 = new Address();
        address1.setUid(uid);
        List<Address> select = addressMapper.select(address1);
        select.forEach(s -> {
            if (s.getId().intValue() == id.intValue()) {
                s.setIfdefault(true);
            } else {
                s.setIfdefault(false);
            }
            addressMapper.updateByPrimaryKey(s);
        });

    }

    public void deleteAddress(Long id) {
        Address address = new Address();
        address.setId(id);
        addressMapper.delete(address);
    }

    public void editAddress(Address address) {
        addressMapper.updateByPrimaryKey(address);

    }

    public Boolean editUserpassword(Useron useron) {
        String username = useron.getOldusername();
        User record = new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        if (user == null) {
            return null;
        }
        String salt = user.getSalt();
        if (!user.getPassword().equals(CodecUtils.md5Hex(useron.getOldpassword(), salt))) {
            return null;
        }
        user.setPassword(CodecUtils.md5Hex(useron.getNewpassword(), salt));
        return userMapper.updateByPrimaryKey(user) == 1;

    }

    public String queryPhone(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        String phone = user.getPhone();
        return phone;
    }

    public Boolean queryCode(String code, String phone) {
        String c = this.stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (c.equals(code)) {
            return true;
        }
        return false;
    }

    public void editPhone(Long id, String phone) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setPhone(phone);
        userMapper.updateByPrimaryKey(user);
    }
    public void addUserDetail(UserDetail userDetail) {
        this.userDetailMapper.insertSelective(userDetail);
    }

    public UserDetail queryUserDetailByUid(Long uid) {

        UserDetail userDetail = new UserDetail();
        userDetail.setUid(uid);
        return userDetailMapper.selectOne(userDetail);
    }

    public void updateUserDetail(UserDetail userDetail) {
        this.userDetailMapper.updateByPrimaryKeySelective(userDetail);
    }
}

